<?php
namespace common\modules\system\models;

use Yii;
use common\helpers\Constants;
use common\core\base\BaseActiveRecord;

/**
 * This is the model class for table "{{%menu}}".
 *
 * @property integer $id
 * @property integer $parent_id
 * @property string $category_id
 * @property string $name
 * @property string $url
 * @property string $target
 * @property string $description
 * @property string $icon
 * @property integer $status
 * @property integer $sort
 */
class Menu extends BaseActiveRecord
{

    const CACHE_PREFIX = 'menu_';

    public function behaviors()
    {
        return [
            'treeBehavior' => [
                'class' => 'common\behaviors\TreeBehavior'
            ]
        ];
    }

    public function init()
    {
        $this->target = Constants::TARGET_SELF;
        $this->status = Constants::STATUS_ENABLE;
        
        parent::init();
    }

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%menu}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [
                [
                    'parent_id',
                    'category_id',
                    'name',
                    'url'
                ],
                'required'
            ],
            [
                [
                    'parent_id',
                    'status',
                    'sort'
                ],
                'integer'
            ],
            [
                [
                    'name',
                    'target',
                    'category_id'
                ],
                'string',
                'max' => 64
            ],
            [
                [
                    'url',
                    'description',
                    'icon'
                ],
                'string',
                'max' => 512
            ]
        ];
    }
    
    public static function getAttributeLabels($attribute = null)
    {
        $items = [
            'id' => 'ID',
            'parent_id' => '父结点',
            'category_id' => '分类',
            'name' => '名称',
            'url' => '链接地址',
            'target' => '打开方式',
            'targetText' => '打开方式',
            'description' => '描述',
            'icon' => '图标',
            'status' => '状态',
            'statusText' => '状态',
            'sort' => '排序'
        ];
        return \common\helpers\ArrayHelper::getItems($items, $attribute);
    }
    
    public function getParent()
    {
        $this->hasOne(Menu::className(), ['id' => 'parent_id']);
    }

    public function getTargetText()
    {
        return Constants::getTargetItems($this->target);
    }

    private static function getArrayTreeInternal($category, $parentId = null, $level = 0)
    {
        $children = self::findAll([
            'category_id' => $category,
            'parent_id' => $parentId
        ], 'sort asc');
        
        $items = [];
        foreach ($children as $child) {
            $child->level = $level;
            $items[$child['id']] = $child;
            $temp = self::getArrayTreeInternal($category, $child->id, $level + 1);
            $items = array_merge($items, $temp);
        }
        
        return $items;
    }

    public static function getMenusByCategory($category, $parentId = null, $fromCache = false)
    {
        $cachekey = self::CACHE_PREFIX . $category;
        
        $values = $fromCache ? getCache($cachekey) : false;
        
        if ($values === false) {
            $values = self::getArrayTreeInternal($category, $parentId, 0);
            setCache($cachekey, $values);
        }
        return $values;
    }

    public static function clearCachedMenus($category)
    {
        $cachekey = self::CACHE_PREFIX . $category;
        deleteCache($cachekey);
    }

    public static function getChildren($category, $parentId = null, $status = 1)
    {
        $items = [];
        $menus = self::getMenusByCategory($category);
        foreach ($menus as $menu) {
            if ($menu->parent_id == $parentId) {
                if ($status && $menu->status !== 1) {
                    continue;
                }
                $items[] = $menu;
            }
        }
        return $items;
    }

    public static function getArrayTree($category)
    {
        return self::getMenusByCategory($category);
    }
    
    /**
     * Get root menu
     * @return string
     */
    public static function getRootMenu($id)
    {
        $menu = Menu::findOne(['id' => $id]);
        if($menu->parent_id > 0){
            $menu = Menu::getRootMenu($menu->parent_id);
        }
        return $menu;
    }

    public function beforeDelete()
    {
        $childrenIds = $this->getChildrenIds();
        self::deleteAll([
            'id' => $childrenIds
        ]);
        return true;
    }

    public function clearCache()
    {
        self::clearCachedMenus($this->category_id);
    }
}
